<template>
  <a-card :bordered="false">
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" :hidden="disabled" type="primary" icon="plus" :disabled="isDisabledAuth('erpPurchaseContractSupplies:add')">新增</a-button>
      <!-- <a-button @click="handleBatchDelete" :hidden="disabled" :disabled="selectedRowKeys&&selectedRowKeys.length?false:true">批量删除</a-button> -->
      <a-popconfirm title="确定删除吗?" @confirm="() => handleBatchDelete()" :disabled="selectedRowKeys&&selectedRowKeys.length?false:true">
        <a-button :hidden="disabled" :disabled="selectedRowKeys&&selectedRowKeys.length?false:true">批量删除</a-button>
      </a-popconfirm>
      <a-button
        @click="handleShopping"
        :hidden="disabled"
        :disabled="isDisabled">导入定标单关联采购物料清单</a-button>
      <a-button @click="handlePay" :hidden="disabled">导入采购清单</a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{x: scrollX}"
        bordered
        :components="draggableComponent"
        rowKey="key"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="false"
        :loading="loading"
        :rowSelection="disabled?null:{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">
        <span slot="action" slot-scope="text, record">
          <a-button
            class="ruleButton"
            :ghost="true"
            type="primary"
            icon="edit"
            :hidden="disabled"
            @click="handleEdit(record)"
            :disabled="isDisabledAuth('erpPurchaseContractSupplies:edit')"
          />
          <a-divider type="vertical" :hidden="disabled"/>
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.key)">
            <a-button
              :hidden="disabled"
              class="ruleButton"
              :ghost="true"
              type="primary"
              icon="delete"
              :disabled="isDisabledAuth('erpPurchaseContractSupplies:delete')"/>
          </a-popconfirm>
        </span>

      </a-table>
    </div>

    <erp-purchase-contract-supplies-modal @dataOne="dataOne" ref="modalForm" @ok="modalFormOk"></erp-purchase-contract-supplies-modal>
    <SelectCannibalizeInput billStatus='1,2' :isHandleShopping="isHandleShopping" ref="cannibalizeInput" :value="[]" @back="onCannibalizeBack"></SelectCannibalizeInput>
    <SelectApplyFormInput :isHandleShopping="isHandleShopping" ref="applyFormInput" @back="onApplyFormBack"></SelectApplyFormInput>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import ErpPurchaseContractSuppliesModal from './ErpPurchaseContractSuppliesModal'
  import { DisabledAuthFilterMixin } from '@/mixins/DisabledAuthFilterMixin'
  import AuditModal from '@/views/scy/components/AuditModal'
  import { filterObj } from '@/utils/util'
  import { getAction } from '@/api/manage'
  import Vue from 'vue'
  import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
  import SelectCannibalizeInput from '@views/scy/components/SelectCannibalizeInput';
  import SelectApplyFormInput from '@views/scy/components/SelectApplyFormInput';
  import { DragResizable } from '@/mixins/DragResizable'
  export default {
    name: 'ErpPurchaseContractSuppliesList',
    mixins: [mixinDevice, DisabledAuthFilterMixin, DragResizable],
    components: {
      ErpPurchaseContractSuppliesModal,
      AuditModal,
      SelectCannibalizeInput,
      SelectApplyFormInput
    },
    props: {
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        isHandleShopping: false,
        isCannibalizeDisabled: false,
        isApplyDisabled: false,
        params: {
          billId: null
        },
        /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
        queryParam: {},
        /* 数据源 */
        dataSource: [],
        /* 分页参数 */
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30', '50', '100', '200'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        /* 排序参数 */
        isorter: {
          column: 'createTime',
          order: 'desc'
        },
        /* 筛选参数 */
        filters: {},
        /* table加载状态 */
        loading: false,
        /* table选中keys */
        selectedRowKeys: [],
        /* table选中records */
        selectionRows: [],
        /* 查询折叠 */
        toggleSearchStatus: false,
        /* 高级查询条件生效状态 */
        superQueryFlag: false,
        /* 高级查询条件 */
        superQueryParams: '',
        /** 高级查询拼接方式 */
        superQueryMatchType: 'and',
        iconStyle: { 'font-size': '18px', 'cursor': 'pointer' },
        colsettings: ':colsettings',
        description: '物料信息管理页面',
        // 表头
        columns: [],
        // 列设置
        settingColumns: [],
        // 列定义
        defColumns: [
          {
            title: '序号',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '采购大类',
            align: 'center',
            dataIndex: 'provisionBroad',
            ellipsis: true,
            width: 80,
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['provisionBroad'], text + '')
              }
            }
          },
          {
            title: '采购小类',
            align: 'center',
            dataIndex: 'provisionSmall',
            ellipsis: true,
            width: 80,
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['provisionSmall'], text + '')
              }
            }
          },
          {
            title: '物料编号',
            align: 'center',
            ellipsis: true,
            width: 80,
            dataIndex: 'materialBillId'

          },
          {
            title: '物料名称',
            align: 'center',
            ellipsis: true,
            width: 80,
            dataIndex: 'materialName',
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['materialName'], text + '')
              }
            }
          },
          {
            title: '品牌',
            align: 'center',
            dataIndex: 'brand',
            width: 80,
            ellipsis: true
          },
          {
            title: '规格型号',
            align: 'center',
            dataIndex: 'specification',
            ellipsis: true,
            width: 80
          },
          {
            title: '单位',
            align: 'center',
            dataIndex: 'unit',
            ellipsis: true,
            width: 80,
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['unit'], text + '')
              }
            }
          },
          {
            title: '数量',
            align: 'center',
            dataIndex: 'amount',
            ellipsis: true,
            width: 80
          },
          {
            title: '单价(元)',
            align: 'center',
            dataIndex: 'unitPrice',
            ellipsis: true,
            width: 80
          },
          {
            title: '总价(元)',
            align: 'center',
            dataIndex: 'totalPrices',
            ellipsis: true,
            width: 80,
            customRender: function (t, r, index) {
              if (r.amount && r.unitPrice) {
                return (Number(r.amount) * Number(r.unitPrice)).toFixed(2)
              } else {
                return '0.00'
              }
            }
          },
          {
            title: '备注',
            align: 'center',
            dataIndex: 'remark',
            width: 80,
            ellipsis: true
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            fixed: 'right',
            width: 150,
            scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action' }
          }
        ],
        url: {
          list: '/api/erp/purchase/contract/erpPurchaseContractSupplies/allList',
          urlListDetail: '/api/erp/purchase/procurement/erpPurchaseApplyInvitationDetail/findInvitationDetail'
        },
        dictOptions: {},
        superFieldList: []
      }
    },
    created() {
      // 加载数据字典信息
      this.initDictConfig();
      this.getSuperFieldList();
      if (!this.disableMixinCreated) {
        this.initColumns()
      }
      if (this.disabled) {
        this.defColumns.pop()
      }
      this.customKey = 'columns'
      this.columnswidth = this.columns.map(val => {
        return val.width
      })
    },
    computed: {
      isDisabled: function () {
        if (!this.isDisabledAuth('erpPurchaseContractSupplies:add')) {
          if (this.dataSource && this.dataSource.length) {
            return true
          } else {
            return false
          }
        } else {
          return true
        }
      }
    },
    methods: {
      initDictConfig() {
        // 采购大类
        initDictOptions('erp_material_category,category_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'provisionBroad', res.result)
          }
        })
        // 采购小类
        initDictOptions('erp_material_category,category_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'provisionSmall', res.result)
          }
        })
        // 物料名称
        initDictOptions('erp_material,material_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'materialName', res.result)
          }
        })
        // 单位
        initDictOptions('unit_type').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'unit', res.result)
          }
        })
        // 供应商
        initDictOptions('erp_omc_customer_manager,mc,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'supplier', res.result)
          }
        })
      },
      getSuperFieldList() {
        let fieldList = [];
        fieldList.push({ type: 'string', value: 'provisionBroad', text: '采购大类', dictCode: '' })
        fieldList.push({ type: 'string', value: 'provisionSmall', text: '采购小类', dictCode: '' })
        fieldList.push({ type: 'string', value: 'materialBillId', text: '物料编号', dictCode: '' })
        fieldList.push({ type: 'string', value: 'materialName', text: '物料名称', dictCode: '' })
        fieldList.push({ type: 'string', value: 'brand', text: '品牌', dictCode: '' })
        fieldList.push({ type: 'string', value: 'specification', text: '规格型号', dictCode: '' })
        fieldList.push({ type: 'string', value: 'unit', text: '单位', dictCode: '' })
        fieldList.push({ type: 'int', value: 'amount', text: '数量', dictCode: '' })
        fieldList.push({ type: 'string', value: 'unitPrice', text: '单价(元)', dictCode: '' })
        fieldList.push({ type: 'string', value: 'totalPrices', text: '总价(元)', dictCode: '' })
        fieldList.push({ type: 'Text', value: 'remark', text: '备注', dictCode: '' })
        fieldList.push({ type: 'string', value: 'calibrationId', text: '定标结果确认单id', dictCode: '' })
        fieldList.push({ type: 'string', value: 'checklistId', text: '采购清单id', dictCode: '' })
        this.superFieldList = fieldList
      },
      getSelectedRowKeys() {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ','
        }
        return ids
      },
      loadData(arg, id) {
        if (!this.url.list) {
          this.$message.error('请设置url.list属性!')
          return
        }
        // 加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1
        }
        this.params = this.getQueryParams() // 查询条件
        if (id) {
          this.params.billId = id
        }
        this.loading = true
        getAction(this.url.list, this.params).then(res => {
          if (res.success) {
            // update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = res.result.records || res.result
            this.dataSource.forEach((item, index) => {
              item.key = index
            })
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
            // 判断是否当前页没有数据且不为第一页
            if (this.dataSource.length == 0 && this.ipagination.current != 1) {
              this.ipagination.current = this.ipagination.current - 1
              this.loadData(this.ipagination.current - 1);
            }
            // update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
          this.loading = false
        })
        this.onClearSelected()
        this[this.customKey].forEach((val, index) => {
          val.width = this[this.customKey + 'width'][index]
        })
      },
      getQueryParams() {
        // 获取查询条件
        let sqp = {}
        if (this.superQueryParams) {
          sqp['superQueryParams'] = encodeURI(this.superQueryParams)
          sqp['superQueryMatchType'] = this.superQueryMatchType
        }
        var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
        param.field = this.getQueryField()
        param.pageNo = this.ipagination.current
        param.pageSize = this.ipagination.pageSize
        return filterObj(param)
      },
      getQueryField() {
        // TODO 字段权限控制
        var str = 'id'
        this.columns.forEach(function (value) {
          // 多表头字段
          if (value.dataIndex == null && value.dataIndex === undefined) {
            value.children.forEach(function (item) {
              str += ',' + item.dataIndex.replace('_dictText', '')
            })
          } else {
            str += ',' + value.dataIndex
          }
        })
        return str
      },

      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectionRows = selectionRows
      },
      onClearSelected() {
        this.selectedRowKeys = []
        this.selectionRows = []
      },
      searchQuery() {
        this.loadData(1)
      },
      superQuery() {
        this.$refs.superQueryModal.show()
      },
      handleDelete: function (key) {
        if (this.dataSource.length == 1) {
          this.dataSource = []
          return
        }
        this.dataSource.splice(key, 1);
        this.dataSource.forEach((item, index) => {
          item.key = index
        })
      },
      handleEdit: function (record) {
        // debugger;
        this.$refs.modalForm.edit(record)
        this.$refs.modalForm.title = '编辑'
        this.$refs.modalForm.disableSubmit = false
      },
      handleAdd: function () {
        this.$refs.modalForm.add()
        this.$refs.modalForm.title = '新增'
        this.$refs.modalForm.disableSubmit = false
      },

      handleBatchDelete () {
        for (let i = 0; i < this.dataSource.length; i++) {
          for (let j = 0; j < this.selectionRows.length; j++) {
            if (this.dataSource[i].materialBillId == this.selectionRows[j].materialBillId) {
              this.dataSource.splice(i, 1)
              i--
              break
            }
          }
        }
        this.onClearSelected()
      },

      // 导入定标单关联采购物料清单
      handleShopping () {
        // this.isHandleShopping = true
        this.$refs.cannibalizeInput.initObj([])
      },

      handlePay () {
        // this.isHandleShopping = true
        this.$refs.applyFormInput.initObj([])
      },

      handleTableChange(pagination, filters, sorter) {
        // 分页、排序、筛选变化时触发
        this.filters = {}
        if (Object.keys(filters).length > 0) {
          for (let key in filters) {
            let value = filters[key].join(',')
            if (value) {
              if (key.indexOf('_dictText') != -1) {
                key = key.substring(0, key.indexOf('_dictText'))
              }
              this.filters[key] = value
            }
          }
        }
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field
          this.isorter.order = sorter.order == 'ascend' ? 'asc' : 'desc'
        }
        this.ipagination = pagination
        this.loadData()
      },
      modalFormOk() {
        // 新增/修改 成功时，重载列表
        this.loadData()
        // 清空列表选中
        this.onClearSelected()
      },
      initColumns() {
        // 权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
        // this.defColumns = colAuthFilter(this.defColumns,'testdemo:');
        if (this.defColumns) {
          var key = this.$route.name + this.colsettings
          let colSettings = Vue.ls.get(key)
          if (colSettings == null || colSettings == undefined) {
            let allSettingColumns = []
            this.defColumns.forEach(function (item, i, array) {
              allSettingColumns.push(item.dataIndex)
            })
            this.settingColumns = allSettingColumns
            this.columns = this.defColumns
          } else {
            Vue.ls.set(key, colSettings, 7 * 24 * 60 * 60 * 1000)
            this.settingColumns = colSettings
            const cols = this.defColumns.filter(item => {
              if (item.key == 'rowIndex' || item.dataIndex == 'action') {
                return true
              }
              if (colSettings.includes(item.dataIndex)) {
                return true
              }
              return false
            })
            this.columns = cols
          }
        }
      },
      dataOne(data, flag) {
        if (flag) {
          this.dataSource.push(data)
          this.dataSource.forEach((item, index) => {
            item.key = index
          })
        } else {
          this.dataSource.splice(data.key, 1, data);
        }
      },
      submitForm() {
        return this.dataSource
      },

      // 点击导入定标单关联采购物料清单回显
      onCannibalizeBack (e) {
        this.onClearSelected()
        this.isApplyDisabled = true
        getAction(this.url.urlListDetail, { calibrationId: e[0].id }).then((res) => {
           if (res.success) {
            this.dataSource = []
            this.dataSource = res.result
            this.dataSource.forEach((item, index) => {
              item.key = index
            })
          }
        })
      },

      // 导入采购清单
      onApplyFormBack (e) {
        this.onClearSelected()
        e.map(value => {
          this.dataSource.push(value)
        })
        this.dataSource = this.arrHeavy(this.dataSource)
        this.dataSource.forEach((item, index) => {
          item.key = index
        })
      },
      // 数组对象去重
      arrHeavy (arr) {
        let newobj = {}
        arr = arr.reduce((preVal, curVal) => {
          newobj[curVal.materialBillId] ? '' : newobj[curVal.materialBillId] = preVal.push(curVal);
          return preVal
        }, [])
        return arr
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>
